package indi.zhifa.recipe.bailan.busy.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;

public abstract class BaseAop {

    private Object getParam(String[] pParameterNames, Object[] pParams ,String pParamName){
        for(int i=0;i<pParams.length;i++){
            if(pParameterNames[i].equals(pParamName)){
                return pParams[i];
            }
        }
        return null;
    }

    protected Object getParam(JoinPoint pJoinPoint, String pParamName){
        Signature signature = pJoinPoint.getSignature();
        String[] parameterNames = ((MethodSignature) signature).getParameterNames();
        Object[] params = pJoinPoint.getArgs();
        Object oVar = getParam(parameterNames,params,pParamName);
        return oVar;
    }

    protected <T> T getParam(JoinPoint pJoinPoint, Class<T> pClassType){
        int idx = getParamIndex(pJoinPoint,pClassType);
        if(idx!=-1){
            return (T)(pJoinPoint.getArgs()[idx]);
        }
        else{
            return null;
        }
    }

    protected <T> int getParamIndex(JoinPoint pJoinPoint, Class<T> pClassType){
        Object[] params = pJoinPoint.getArgs();
        for (int i=0;i<params.length;i++){
            Object param = params[i];
            if(param.getClass().equals(pClassType)){
                return i;
            }
        }
        return -1;
    }
}
